import axios from "axios";

// 请求缓存池
const requestCache = new Map();

interface RequestConfig {
  method: string;
  url: string;
  data: any;
  params?: any;
  keepAlive?: boolean; // 自动清理缓存
  cacheTTL?: number;
}

class RequestPool {
  private pool: Map<string, any>;
  private defaultTTL: number;

  constructor() {
    this.pool = new Map();
    this.defaultTTL = 5000; // 默认缓存5秒
  }

  getKey(config: RequestConfig) {
    const { method, url, params, data } = config;
    return `${method}-${url}-${JSON.stringify(params || {})}-${JSON.stringify(
      data || {}
    )}`;
  }

  async request(config: RequestConfig) {
    const key = this.getKey(config);
    const now = Date.now();
    if (config.keepAlive === undefined) {
      config.keepAlive = false;
    }
    // 存在未过期的缓存
    if (this.pool.has(key)) {
      const { expire, promise } = this.pool.get(key);
      if (expire > now) return promise;
    }

    // 创建新请求
    const promise = axios(config).finally(() => {
      // 自动清理或保留缓存
      if (!config.keepAlive) {
        this.pool.delete(key);
      }
    });

    // 缓存带有效期
    this.pool.set(key, {
      promise,
      expire: Date.now() + (config.cacheTTL || this.defaultTTL),
    });

    return promise;
  }

  // 手动清除缓存
  clearCache(key: string) {
    this.pool.delete(key);
  }
}

export default new  RequestPool()

// 使用示例
const apiPool = new RequestPool();

function fetchUserData(userId: string) {
  return apiPool.request({
    method: "GET",
    url: "/api/user",
    params: { id: userId },
    data: {},
    cacheTTL: 10000, // 自定义缓存时间
  });
}
